package com.acme.bankapp.service.bank.utils;

import com.acme.bankapp.domain.bank.account.AccountType;
import com.acme.bankapp.domain.bank.client.Gender;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class parse line and get client info
 *
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class ClientInfoParser {
    private AccountType accountType;
    private double balance;
    private double overdraft;
    private String clientName;
    private Gender gender;

    private static String doubleRegExp = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?";
    private static String clientInfoRegExp = "^accounttype=(?<type>[cs]);"
            + "balance=(?<balance>" + doubleRegExp + ");"
            + "overdraft=(?<overdraft>" + doubleRegExp + ");"
            + "name=(?<name>.+);"
            + "gender=(?<gender>[mf]);$";

    static Pattern pattern = Pattern.compile(clientInfoRegExp);

    public ClientInfoParser(String line) throws ParseClientInfoException {
        Matcher matcher = pattern.matcher(line);

        if (!matcher.matches()) {
            throw new ParseClientInfoException(String.format("Can't parse line: '%s'", line));
        }

        accountType = matcher.group("type").equals("s") ? AccountType.SAVING : AccountType.CHECKING;
        balance = Double.parseDouble(matcher.group("balance"));
        overdraft = Double.parseDouble(matcher.group("overdraft"));
        clientName = matcher.group("name");
        gender = matcher.group("gender").equals("m") ? Gender.MALE : Gender.FEMALE;
    }

    public AccountType getAccountType() {
        return accountType;
    }

    public double getBalance() {
        return balance;
    }

    public double getOverdraft() {
        return overdraft;
    }

    public String getClientName() {
        return clientName;
    }

    public Gender getGender() {
        return gender;
    }
}
